package com.bawei.module_notice.ui.adapter


import android.content.Context
import android.graphics.drawable.Drawable
import android.graphics.drawable.GradientDrawable
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.AsyncListDiffer
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.bawei.module_notice.R
import com.bawei.module_notice.databinding.ItemLoadingFooterBinding
import com.bawei.module_notice.databinding.ItemNoticeBinding
import com.bawei.module_notice.model.NoticeModel


class NoticeAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
    // 定义点击监听器（参数为当前点击的公告数据）
    interface OnItemClickListener {
        fun onItemClick(notice: NoticeModel)
    }

    // 暴露给外部设置的监听器变量
    var onItemClickListener: OnItemClickListener? = null
    // 视图类型
    private val TYPE_ITEM = 1
    private val TYPE_FOOTER = 2

    // 加载状态
    sealed class LoadState {
        object Loading : LoadState()
        object NotLoading : LoadState()
    }

    private var loadState: LoadState = LoadState.NotLoading
    private val differ = AsyncListDiffer(this, NoticeDiffCallback())

    // 设置加载状态（触发底部布局更新）
    fun setLoadState(state: LoadState) {
        loadState = state
        notifyItemChanged(itemCount) // 通知底部项刷新
    }

    // 提交数据
    fun submitList(data: List<NoticeModel>?) = differ.submitList(data)

    // 判断视图类型（底部加载布局）
    override fun getItemViewType(position: Int): Int {
        // 关键：只有数据非空 + 加载中，才显示 footer
        val hasData = differ.currentList.isNotEmpty()
        val isLoading = loadState is LoadState.Loading
        return if (hasData && position == differ.currentList.size && isLoading) {
            TYPE_FOOTER
        } else {
            TYPE_ITEM
        }
    }

    // 创建ViewHolder（区分普通项和底部加载项）
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return when (viewType) {
            TYPE_ITEM -> {
                val binding = ItemNoticeBinding.inflate(
                    LayoutInflater.from(parent.context),
                    parent,
                    false
                )
                NoticeViewHolder(binding)
            }
            TYPE_FOOTER -> {
                val binding = ItemLoadingFooterBinding.inflate(
                    LayoutInflater.from(parent.context),
                    parent,
                    false
                )
                FooterViewHolder(binding)
            }
            else -> throw IllegalArgumentException("Invalid view type")
        }
    }

    // 绑定数据（底部项仅显示加载动画）
    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        when (holder) {
            is NoticeViewHolder -> {
                val notice = differ.currentList[position]
                holder.binding.notice = notice
                holder.binding.executePendingBindings()
                // 列表项点击事件：触发外部监听器
                holder.binding.root.setOnClickListener {
                    onItemClickListener?.onItemClick(notice)
                }
            }
            is FooterViewHolder -> {
                holder.bind() // 底部加载布局，无需数据
            }
        }
    }

    // 数据项总数（含底部加载项）
    override fun getItemCount(): Int {
        // 数据量 + footer（加载中时显示）
        val footerCount = if (differ.currentList.isNotEmpty() && loadState is LoadState.Loading) 1 else 0
        return differ.currentList.size + footerCount
    }

    // 普通项ViewHolder
    class NoticeViewHolder(val binding: ItemNoticeBinding) : RecyclerView.ViewHolder(binding.root)

    // 底部加载项ViewHolder
    class FooterViewHolder(val binding: ItemLoadingFooterBinding) : RecyclerView.ViewHolder(binding.root) {
        fun bind() {
            binding.progressBar.visibility = View.VISIBLE // 显示加载动画
        }
    }

    // DiffUtil回调（优化数据更新）
    class NoticeDiffCallback : DiffUtil.ItemCallback<NoticeModel>() {
        override fun areItemsTheSame(old: NoticeModel, new: NoticeModel) = old.id == new.id
        override fun areContentsTheSame(old: NoticeModel, new: NoticeModel) = old == new
    }
}